package com.fsds.crem.core.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author King
 * 
 */
public class SendMailUtil {

	private static final String hostName = ResourceUtils.getConfigByName("SENDER_EMAIL_HOST_NAME");
	private static final String port = ResourceUtils.getConfigByName("SENDER_EMAIL_PORT");
	private static final String from = ResourceUtils.getConfigByName("SENDER_EMAIL_ADDRESS");
	private static final String fromName = ResourceUtils.getConfigByName("SENDER_EMAIL_NAME");
	private static final String charSet = "utf-8";
	private static final String username = ResourceUtils.getConfigByName("SENDER_EMAIL_ADDRESS");
	private static final String password = ResourceUtils.getConfigByName("SENDER_EMAIL_PASSWORD");
	private static Map<String, String> hostMap = new HashMap<String, String>();
	static {
		// 126
		hostMap.put("smtp.126", "smtp.126.com");
		// qq
		hostMap.put("smtp.qq", "smtp.qq.com");

		// 163
		hostMap.put("smtp.163", "smtp.163.com");

		// sina
		hostMap.put("smtp.sina", "smtp.sina.com.cn");

		// tom
		hostMap.put("smtp.tom", "smtp.tom.com");

		// 263
		hostMap.put("smtp.263", "smtp.263.net");

		// yahoo
		hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");

		// hotmail
		hostMap.put("smtp.hotmail", "smtp.live.com");

		// gmail
		hostMap.put("smtp.gmail", "smtp.gmail.com");
		hostMap.put("smtp.port.gmail", "465");
	}

	public static String getHost(String email) throws Exception {

		Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
		Matcher matcher = pattern.matcher(email);
		String key = "unSupportEmail";
		if (matcher.find()) {
			key = "smtp." + matcher.group(1);
		}
		if (hostMap.containsKey(key)) {
			return hostMap.get(key);
		}
		else {
			throw new Exception("unSupportEmail");
		}
	}

	public static int getSmtpPort(String email) throws Exception {

		Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
		Matcher matcher = pattern.matcher(email);
		String key = "unSupportEmail";
		if (matcher.find()) {
			key = "smtp.port." + matcher.group(1);
		}
		if (hostMap.containsKey(key)) {
			return Integer.parseInt(hostMap.get(key));
		}
		else {
			return 25;
		}
	}

	/**
	 * 发送模板邮件
	 * 
	 * @param toMailAddr
	 *          收信人地址
	 * @param subject
	 *          email主题
	 * @param templatePath
	 *          模板地址
	 * @param map
	 *          模板map
	 */
	/**
	 * @param toMailAddr
	 * @param subject
	 * @param templatePath
	 * @param map
	 */
	/**
	 * @param toMailAddr
	 * @param subject
	 * @param templatePath
	 * @param map
	 */
	/**
	 * @param toMailAddr
	 * @param subject
	 * @param templatePath
	 * @param map
	 */
	@SuppressWarnings("deprecation")
	public static boolean sendFtlMail(List<String> toMailAddrs, String subject, 
			String templateName, Map<String, Object> map, String attachmentUrl, String attachmentName) {

		boolean flag = true;
		Template template = null;
		Configuration freeMarkerConfig = null;
		HtmlEmail hemail = new HtmlEmail();
		try {
//			hemail.setHostName(getHost(from));
//			hemail.setSmtpPort(getSmtpPort(from));
			hemail.setHostName(hostName);
			hemail.setSmtpPort(Integer.parseInt(port));
			hemail.setCharset(charSet);
			String s2 = new String(fromName.getBytes("ISO-8859-1"), "utf-8");
			hemail.setFrom(from, s2);
			hemail.setAuthentication(username, password);
			hemail.setSubject(subject);
			hemail.setSSL(Boolean.TRUE);
			
			// 添加多个收件人
			for(String addr : toMailAddrs){
				hemail.addTo(addr);
			}
			
			if(StringUtils.isNotEmpty(attachmentUrl) && StringUtils.isNotEmpty(attachmentName)) {
				
				// set附件
				EmailAttachment attachment = new EmailAttachment();//创建附件  
		        //attachment.setPath(MimeUtility.encodeText(attachmentUrl,"GBK","B"));//本地附件，绝对路径
		        attachment.setPath(attachmentUrl);//本地附件，绝对路径
				
		        //attachment.setURL(new URL("http://www.baidu.com/moumou附件"));//可添加网络上的附件  
		        attachment.setDisposition(EmailAttachment.ATTACHMENT);
		        attachment.setName(MimeUtility.encodeWord(attachmentName));
		        //attachment.setName(attachmentName);//附件名称  
		        hemail.attach(attachment);//添加附件到邮件,可添加多个  
			}
			
			
			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFileRootPath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(templateName, new Locale("Zh_cn"), "UTF-8");
			// 模板内容转换为string
			String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			//hemail.setMsg(htmlText);
			hemail.setHtmlMsg(htmlText);
			hemail.send();
		}
		catch (Exception e) {
			
			flag = false;
			
			e.printStackTrace();
		}
		
		return flag;
	}

	/**
	 * 发送普通邮件
	 * 
	 * @param toMailAddr
	 *          收信人地址
	 * @param subject
	 *          email主题
	 * @param message
	 *          发送email信息
	 */
	public static void sendCommonMail(String toMailAddr, String subject, String message) {

		HtmlEmail hemail = new HtmlEmail();
		try {
//			hemail.setHostName(getHost(from));
//			hemail.setSmtpPort(getSmtpPort(from));
			hemail.setHostName(hostName);
			hemail.setSmtpPort(Integer.parseInt(port));
			hemail.setCharset(charSet);
			hemail.addTo(toMailAddr);
			hemail.setFrom(from, fromName);
			hemail.setAuthentication(username, password);
			hemail.setSubject(subject);
			hemail.setMsg(message);
			hemail.send();
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}

	@SuppressWarnings("deprecation")
	public static String getHtmlText(String templateName, Map<String, Object> map) {

		Template template = null;
		String htmlText = "";
		try {
			Configuration freeMarkerConfig = null;
			freeMarkerConfig = new Configuration();
			freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFileRootPath()));
			// 获取模板
			template = freeMarkerConfig.getTemplate(templateName, new Locale("Zh_cn"), "UTF-8");
			// 模板内容转换为string
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return htmlText;
	}

	public static String getFileRootPath() {

		return ResourceUtils.getSysPath() + "template/";
	}

}